<template>
  <view class="content">
    <u-form ref="uForm" :errorType="errorType" :model="form">
      <view class="formBox">
        <view class="title">基础信息</view>
        <u-form-item label="活动标题 " label-width="200rpx" prop="peerTitle" required>
          <u-input v-model="form.peerTitle" input-align="right" placeholder=" 请输入名称"/>
        </u-form-item>
        <u-form-item label="活动开始时间" label-width="200rpx" prop="timeStart" required>
          <u-input v-model="form.timeStart" disabled input-align="right" placeholder="请选择时间"
                   @click="openTimeShow('timeStart')"/>
        </u-form-item>
        <u-form-item label="活动结束时间" label-width="200rpx" prop="timeEnd" required>
          <u-input v-model="form.timeEnd" disabled input-align="right" placeholder="请选择时间"
                   @click="openTimeShow('timeEnd')"/>
        </u-form-item>
        <u-form-item label="虚拟参加人数" label-width="200rpx" prop="inventedJoinNumber">
          <u-input v-model="form.inventedJoinNumber" input-align="right" placeholder="请输入虚拟参加人数" type="digit"/>
        </u-form-item>
        <u-form-item label="活动门店" label-width="150rpx" prop="joinStores" required>
          <view
              v-if="form.joinStores && form.joinStores.split(',').length && form.joinStores.length != 0 && selectStore.length == 0"
              style="width: 100%;"
              @click="goselectStore"
          >
            已选择{{ form.joinStores.split(',').length }}家门店
          </view>
          <view v-else-if="selectStore.length != 0" style="width: 100%;" @click="goselectStore">已选择{{
              selectStore.length
            }}家门店
          </view>
          <view v-else style="width: 100%;" @click="goselectStore">请选择门店</view>
        </u-form-item>
        <u-form-item label="邀请设置" label-width="150rpx" prop="invite" required>
          <u-radio-group v-model="form.invite">
            <u-radio
                v-for="(item, index) in invitations"
                :key="index"
                :disabled="item.disabled"
                :name="item.value"
                size="50"
                @change="e => radioChange(item.value, 'invite')"
            >
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
      </view>
      <view class="formBox">
        <view class="title">活动信息</view>
        <u-form-item label="活动封面" label-position="top" label-width="200rpx" prop="coverImage"
                     required><view class="remark">支持格式jpg/png，宽高比为4:3，仅限一张图片</view>
          <u-upload
              :action="action"
              :auto-upload="true"
              :file-list="fileList"
              :max-size="5 * 1024 * 1024"
              :show-progress="false"
              height="160"
              max-count="1"
              name="files"
              width="160"
              @on-success="onSuccess"
              @on-list-change="onListChange"
          ></u-upload>
        </u-form-item>
        <u-form-item label="分享封面" label-position="top" label-width="150rpx" prop="shareImage"
                     required>
          <view class="remark">支持格式jpg/png，宽高比为5:4，仅限一张图片</view>
          <u-upload
              :action="action"
              :auto-upload="true"
              :file-list="fileList2"
              :max-size="5 * 1024 * 1024"
              :show-progress="false"
              height="160"
              max-count="1"
              name="files"
              width="160"
              @on-success="onSuccess2"
              @on-list-change="onListChange2"
          ></u-upload>
        </u-form-item>
        <u-form-item label="活动内容" label-width="150" prop="peerContent" required>
          <view style="width: 100%;" @click="goShopDetail">{{
              form.peerContent.length > 0 ? '修改活动内容' : '请输入活动内容'
            }}
          </view>
          <!-- <u-input input-align="right"  placeholder="请输入商品详情" disabled v-model="model.details" @click="goShopDetail" type="text"></u-input> -->
        </u-form-item>
      </view>
      <view class="formBox">
        <view class="title f-c-sb">
          活动奖品
          <u-icon color="#2979ff" name="plus-circle-fill" size="35" @click="showPopup(1)"></u-icon>
        </view>
        <view class="shopList">
          <view v-for="(item, itemIndex) in form.peerGsDtos" :key="itemIndex">
            <u-form-item label="奖品类型" label-width="150rpx" prop="peerType" required>
              <u-input v-model="peerTypes[item.peerType-1].name" disabled input-align="right" placeholder=" 请输入奖品名称"/>

            </u-form-item>
            <u-form-item v-if="item.peerType == 1" label="奖品名称 " label-width="200rpx" required>
              <u-input v-model="item.peerName" disabled input-align="right" placeholder=" 请输入奖品名称"/>
            </u-form-item>
            <u-form-item v-if="item.peerType == 2" label="兑换方式 " label-width="200rpx" required>
              <u-input disabled input-align="right" placeholder=" 请输入奖品名称" value="组队成功自动发放优惠券"/>
            </u-form-item>
            <u-form-item v-if="item.peerType == 2" :prop="'couponId'+itemIndex" label="选择优惠券 " label-width="200rpx"
                         required>
              <u-input v-model="item.peerName" disabled input-align="right" placeholder=" 请选择"/>
              <u-icon slot="right" name="arrow-right" size="28"></u-icon>
            </u-form-item>
            <u-form-item label="组队人数(最少二人以上) " label-width="350rpx" required>
              <u-input v-model="item.peerNumber" disabled input-align="right" placeholder=" 请输入组队人数" type="number"/>
            </u-form-item>
            <u-form-item label="赠送人数 " label-width="200rpx" required>
              <u-input v-model="item.peerGive" disabled input-align="right" placeholder=" 请输入赠送人数" type="number"/>
            </u-form-item>
            <u-form-item label="奖品发放库存 " label-width="200rpx" required>
              <u-input v-model="item.peerStock" disabled input-align="right" placeholder=" 请输入奖品发放库存" type="number"/>
            </u-form-item>
            <u-form-item
                label="奖品实物照片"
                label-position="top"
                label-width="200rpx"
                required
            >
              <u-image :src="imagePath+item.peerUrl" height="160rpx"
                       width="160rpx"></u-image>
            </u-form-item>
            <u-form-item>
              <view class="f-c-fe">
                <view v-if="itemIndex > 0" slot="right" style="margin: 0 15rpx;" @click="deleteFn(itemIndex)">
                  <u-icon name="trash-fill" size="36"></u-icon>
                </view>
                <view slot="right" style="margin: 0 15rpx;" @click="showPopup(2,itemIndex)">
                  <u-icon name="edit-pen-fill" size="36"></u-icon>
                </view>
              </view>
            </u-form-item>
          </view>
        </view>
      </view>
    </u-form>
    <view class="f-c-sa btn">
      <u-button plain ripple size="medium" type="primary" @click="submit(2)">预览效果</u-button>
      <u-button ripple size="medium" type="primary" @click="submit(1)">完成创建</u-button>
    </view>
    <u-popup v-model="show" border-radius="22" closeable mode="bottom" safe-area-inset-bottom>
      <view class="formBox-wrapper">
        <view class="formBox">
          <u-form ref="uShop" :model="shop">
            <u-form-item label="奖品类型" label-width="150rpx" prop="peerType" required>
              <u-radio-group v-model="shop.peerType">
                <u-radio
                    v-for="(items, indexs) in peerTypes"
                    :key="indexs"
                    :disabled="items.disabled"
                    :name="items.value"
                    size="50"
                    @change="e => radioChange(items.value, 'peerType', 1)"
                >
                  {{ items.name }}
                </u-radio>
              </u-radio-group>
            </u-form-item>
            <u-form-item v-if="shop.peerType == 1" label="奖品名称 " label-width="200rpx" prop="peerName" required>
              <u-input v-model="shop.peerName" input-align="right" placeholder=" 请输入奖品名称"/>
            </u-form-item>
            <u-form-item v-if="shop.peerType == 2" label="兑换方式 " label-width="200rpx" required>
              <u-input disabled input-align="right" placeholder=" 请输入奖品名称" value="组队成功自动发放优惠券"/>
            </u-form-item>
            <u-form-item v-if="shop.peerType == 2" label="选择优惠券 " label-width="200rpx" prop="couponId" required>
              <u-input v-model="shop.peerName" disabled input-align="right" placeholder=" 请选择"
                       @click="selcoupon(itemIndex)"/>
              <u-icon slot="right" name="arrow-right" size="28"></u-icon>
            </u-form-item>
            <u-form-item label="组队人数(最少二人以上) " label-width="350rpx" prop="peerNumber" required>
              <u-input v-model="shop.peerNumber" input-align="right" placeholder=" 请输入组队人数" type="number"/>
            </u-form-item>
            <u-form-item label="赠送人数 " label-width="200rpx" prop="peerGive" required>
              <u-input v-model="shop.peerGive" input-align="right" placeholder=" 请输入赠送人数" type="number"/>
            </u-form-item>
            <u-form-item label="奖品发放库存 " label-width="200rpx" prop="peerStock" required>
              <u-input v-model="shop.peerStock" input-align="right" placeholder=" 请输入奖品发放库存" type="number"/>
            </u-form-item>
            <u-form-item
                prop="peerUrl"
                label="奖品实物照片"
                label-position="top"
                label-width="200rpx"
                required
            >
          <view class="remark">支持格式jpg/png，宽高比为1:1，仅限一张图片</view>
              <u-upload
                  ref="uUpload"
                  :action="action"
                  :auto-upload="true"
                  :file-list="shop.fileList"
                  :max-size="5 * 1024 * 1024"
                  :show-progress="false"
                  height="160"
                  max-count="1"
                  name="files"
                  width="160"
                  @on-success="onSuccess4"
                  @on-list-change="onListChange4"
              ></u-upload>
            </u-form-item>
          </u-form>
        </view>

        <view class="lxdBtn" @click="save">保存</view>
      </view>
    </u-popup>
    <u-toast ref="uToast"/>
    <u-picker v-model="timeShow" :params="params" mode="time" placeholder="请选择时间" @confirm="selectTime"></u-picker>
  </view>
</template>

<script>
import {peerEdit, peerEditEcho} from '../../api/marketing';
import {mapGetters} from 'vuex';
import {dateFormat} from '@/utils/common/dateTime';

export default {
  data() {
    return {
		imagePath:this.$imagePath,
      editStatus: 1,
      editStatusIndex: 1,
      show: false,
      id: '',
      timeType: '',
      timeShow: false,
      invitations: [
        {
          name: '无限制',
          value: 1,
          disabled: false
        },
        {
          name: '仅能邀请新客',
          value: 2,
          disabled: false
        }
      ],
      peerTypes: [
        {
          name: '实物',
          value: 1,
          disabled: false
        },
        {
          name: '卡卷',
          value: 2,
          disabled: false
        }
      ],
      action: 'https://sj.shopec.com.cn/hty-manage-api/upload/files',
      errorType: ['message'],
      fileList2: [],
      fileList: [],
      params: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false,
        timestamp: true
      },
      form: {
        coverImage: '',
        inventedJoinNumber: '',
        invite: 1,
        joinStores: '',
        peerContent: '',
        peerGsDtos: [],
        peerTitle: '',
        shareImage: '',
        storeBasicId: '',
        timeEnd: '',
        timeStart: ''
      },
      shop: {
        couponId: '',
        peerGive: '',
        peerName: '',
        peerNumber: '',
        peerStock: '',
        peerType: 1,
        peerUrl: '',
        fileList: []
      },
      rulesShop: {
        peerGive: [
          {
            validator: (rule, value, callback) => {
              return this.$u.test.digits(value);
            },
            message: '请输入正整数',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }, {
            validator: (rule, value, callback) => {
              if (value > this.shop.peerNumber) {

                return false

              } else {
                callback()
              }
            },
            message: '赠送人数不能大于组队人数',
          }
        ],
        peerName: [
          {
            required: true,
            message: '请输入',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        peerContent: [
          {
            validator: (rule, value, callback) => {
              console.log(value);
              if (!value) {
                return false;
              } else {
                callback();
              }
            },
            message: '请输入',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        peerNumber: [
          {
            validator: (rule, value, callback) => {
              return this.$u.test.digits(value);

            },
            message: '请输入数字',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          },
          // 自定义规则判断是否包含字母"A"
          {
            validator: (rule, value, callback) => {
              if (value < 2) {
                return false;
              } else {
                callback()
              }
            },
            message: '最低不能少于两个人',
            trigger: ['change', 'blur']
          }
        ],
        couponId: [
          {
            required: true,
            message: '请选择优惠券',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        peerUrl: [
          {
            required: true,
            message: '请上传图片',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        peerStock: [
          {
            validator: (rule, value, callback) => {
              return this.$u.test.digits(value);

            },
            message: '请输入',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ]
      },
      rules: {
        peerTitle: [
          {
            validator: (rule, value, callback) => {
              console.log(value);
              if (!value) {
                return false;
              } else {
                callback();
              }
            },
            message: '请输入',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        timeStart: [
          {
            required: true,
            message: '请选择时间',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        timeEnd: [
          {
            required: true,
            message: '请选择时间',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],

        coverImage: [
          {
            validator: (rule, value, callback) => {
              console.log(value);
              if (!value) {
                return false;
              } else {
                callback();
              }
            },
            message: '请上传图片',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        shareImage: [
          {
            validator: (rule, value, callback) => {
              console.log(value);
              if (!value) {
                return false;
              } else {
                callback();
              }
            },
            message: '请上传图片',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ]


      }
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'selectStore', 'selectStaff'])
  },
  onLoad(option) {
    if (JSON.parse(option.param) && JSON.parse(option.param).id) {
      this.id = JSON.parse(option.param).id;
    }
  },
  onShow() {
    if (this.$get('addHtml')) {
      this.form.peerContent = this.$get('addHtml');
    }
    uni.$on('setCardData', data => {
      this.shop.couponId = data.coupon[0].id;
      this.shop.peerName = data.coupon[0].name;
    });
  },
  onUnload() {
    this.$remove('addHtml');
    this.$store.commit('setSelectStore', []);

  },
  methods: {
    getData() {
      peerEditEcho({id: this.id}).then(res => {
        var peerGsEntities = res.data.peerGsEntities;
        peerGsEntities.forEach((val, index) => {
          peerGsEntities[index].fileList = [];
          if (val.peerUrl.indexOf(',') != -1) {
            val.peerUrl.split(',').forEach((item, i) => {
              var Obj = {
                url: '',
                error: false, // 上传失败，此值为true
                progress: 100 // 0-100之间的值
              };
              Obj.url = this.$imagePath + item;
              peerGsEntities[index].fileList.push(Obj);
            });
          } else {
            var Obj = {
              url: '',
              error: false, // 上传失败，此值为true
              progress: 100 // 0-100之间的值
            };
            Obj.url = this.$imagePath + val.peerUrl;
            peerGsEntities[index].fileList.push(Obj);
          }
        });
        this.form = res.data;
        var urlObj = {
          url: '',
          error: false, // 上传失败，此值为true
          progress: 100 // 0-100之间的值
        };
        urlObj.url = this.$imagePath + res.data.coverImage;
        this.fileList.push(urlObj);
        var urlObj2 = {
          url: '',
          error: false, // 上传失败，此值为true
          progress: 100 // 0-100之间的值
        };
        urlObj2.url = this.$imagePath + res.data.shareImage;
        this.fileList2.push(urlObj2);
        this.form.peerGsDtos = peerGsEntities;

        this.$forceUpdate();
      });

    },
    showPopup(type, index = null) {
      this.editStatus = type
      this.editStatusIndex = index
      if (index !== null) {
        this.shop = JSON.parse(JSON.stringify(this.form.peerGsDtos[index]))
      } else {
        var obj = {
          couponId: '',
          peerGive: '',
          peerName: '',
          peerNumber: '',
          peerStock: '',
          peerType: 1,
          peerUrl: '',
          fileList: []
        };
        this.shop = obj
        this.$forceUpdate()
      }
      this.show = true
      this.$refs.uUpload.clear();

    },
    add() {
      var obj = {
        couponId: '',
        peerGive: '',
        peerName: '',
        peerNumber: '',
        peerStock: '',
        peerType: 1,
        peerUrl: '',
        fileList: []
      };
      this.form.peerGsDtos.push(obj);
    },
    deleteFn(index) {
      this.form.peerGsDtos.splice(index, 1);
    },
    radioChange(e, type, index = null) {
      console.log(e);
      if (index !== null) {
        this.shop[type] = e;
      } else {
        this.form[type] = e;
      }
    },
    goShopDetail() {
      this.$put('addHtml', this.form.peerContent);
      this.$navigateTo('/workbench/shopDetail/shopDetail', {});
    },
    submit(type) {
      if (this.selectStore.length > 0) {
        var str = '';
        this.selectStore.forEach((val, index) => {
          if (index == this.selectStore.length - 1) {
            str = str + val.storeId;
          } else {
            str = str + val.storeId + ',';
          }
        });
        this.form.joinStores = str;
      }
      if (!this.form.joinStores) {
        this.$refs.uToast.show({
          title: '请选择活动门店',
          type: 'error'
        });
      }
      this.form.storeBasicId = this.userInfo.storeBasicId;

      this.$refs.uForm.validate(valid => {
        if (valid) {
          var data = this.form;


          console.log('验证通过', type);
          this.$put('peerDetail', data);
          if (type == 2) {
            this.$navigateTo('./preview', {});
            return;
          }
          peerEdit(data).then(res => {
            if (res.code == 1) {
              this.$put('isCreatStatus', '1');
              uni.switchTab({
                url: '/pages/marketing/marketing'
              });
            } else {
              this.$refs.uToast.show({
                title: res.msg,
                type: 'error'
              });
            }
          });
        } else {
          console.log('验证失败');
        }
      });
    },
    onListChange(lists, index) {
      this.fileList = lists;
    },

    onListChange2(lists, index) {
      this.fileList2 = lists;
    },
    onSuccess(data, index, lists, name) {
      console.log(data, index, lists, name);
      this.form.coverImage = data.data.saveUrl;
    },
    onListChange4(lists, index) {
      this.shop.fileList = lists;
      if (this.shop.fileList.length == 0) {
        this.shop.peerUrl = ''
      }
    },
    onSuccess4(data, index, lists, name) {
      console.log(data, index, lists, name);
      this.shop.peerUrl = data.data.saveUrl;

    },
    onListChange3(lists, name, index) {
      console.log(index);
      this.form.peerGsDtos[index].fileList = lists;
    },
    onSuccess3(data, index, lists, name, itemIndex) {
      console.log(data, index, lists, name);
      var str = '';
      lists.forEach((val, index) => {
        if (index == lists.length - 1) {
          str = str + val.response.data.saveUrl;
        } else {
          str = str + val.response.data.saveUrl + ',';
        }
      });
      this.form.peerGsDtos[itemIndex].peerUrl = str;
    },
    onSuccess2(data, index, lists, name) {
      console.log(data, index, lists, name);
      this.form.shareImage = data.data.saveUrl;
    },
    goselectStore() {
      this.$navigateTo('/pages/selectStore/selectStore', {});
    },
    openTimeShow(type) {
      this.timeType = type;
      this.timeShow = true;
    },
    selcoupon(index) {
      uni.navigateTo({
        url: '/marketing/lottery/coupons?index=' + index
      });
    },

    selectTime(e) {
      console.log(e);
      if (this.timeType == 'timeEnd' && this.form.timeStart.length == 0) {
        this.$refs.uToast.show({
          title: '请选择开始时间',
          type: 'error'
        });
        return;
      } else if (this.timeType == 'timeEnd' && this.form.timeStart.length != 0) {
        var date = new Date(this.form.timeStart);
        if ((e.timestamp + 600) * 1000 < date.getTime()) {
          this.$refs.uToast.show({
            title: '结束时间不能小于开始时间',
            type: 'error'
          });
          return;
        }
      }
      if ((e.timestamp + 600) * 1000 < +new Date()) {
        this.$refs.uToast.show({
          title: '时间不能小于当前时间',
          type: 'error'
        });
        return;
      }
      this.form[this.timeType] = dateFormat(e.timestamp, 'yyyy-MM-dd');
    },
    save() {

      this.$refs.uShop.validate(valid => {
        console.log(valid)
        if (valid) {
          console.log('验证通过');
          if (this.editStatus == 1) {
            this.form.peerGsDtos.push(JSON.parse(JSON.stringify(this.shop)));
          } else if (this.editStatus == 2) {
            this.form.peerGsDtos[this.editStatusIndex] = JSON.parse(JSON.stringify(this.shop));
          }
          this.$refs.uUpload.clear();
          this.show = false;
        } else {
          console.log('验证失败');
        }
      })
    }
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uShop.setRules(this.rulesShop);
    this.$refs.uForm.setRules(this.rules);

    if (this.id) {
      this.getData();
    }
  }
};
</script>
<style scoped>
.btn {
  margin: 50 rpx 0;
}

 .remark {
    font-size: 24rpx;
    color: #888888;
    line-height: 30rpx;
  }
</style>
